// Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.

#![crate_type = "bin"]
#![crate_name = "mkdir"]

static VERS: &'static str = "0.1.0";
static PROG: &'static str = "mkdir";

extern crate getopts;
extern crate util;

use getopts::{Options};
use util::{Status};

use std::fs;
use std::env;
use std::path::{PathBuf};

fn mk_dir(dir: Vec<String>, verbose: bool) {
    for item in dir {
        match fs::create_dir(PathBuf::from(&item)) {
            Ok(_) => {
                if verbose {
                    println!("{}: created directory '{}'", PROG, item);
                }
            },
            Err(e) => {
                util::err(PROG, Status::Error, e.to_string());
            }
        };
    }
}

fn mk_dir_p(dir: Vec<String>, verbose: bool) {
    for item in dir {
        match fs::create_dir_all(PathBuf::from(&item)) {
            Ok(_) => {
                if verbose {
                    println!("{}: created directory '{}'", PROG, item);
                }
            },
            Err(e) => {
                util::err(PROG, Status::Error, e.to_string());
            }
        };
    }
}

fn print_usage(prog: &str, opts: Options) {
    let brief = format!("Usage: {} [OPTION]", prog);
    print!("{}", opts.usage(&brief));
    util::exit(Status::Ok);
}

fn main() {
    let args: Vec<String>  = env::args().collect();
    let prog = "mkdir";
    let mut opts = Options::new();

    opts.optflag("h", "help", "Print the help menu");
    opts.optflag("", "version", "Print the version of mkdir");
    opts.optflag("v", "verbose", "Print the name of each created directory");
    opts.optflag("p", "parents", "No error if existing, make parent directories as needed");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => {
            util::err(PROG, Status::OptError, f.to_string());
            panic!(f);
        }
    };

    let verb = matches.opt_present("v");

    if matches.opt_present("p") {
        mk_dir_p(matches.free, verb);
    } else if matches.opt_present("h") {
        print_usage(&prog, opts);
    } else if matches.opt_present("version") {
        util::copyright(PROG, VERS, "2015", vec!["Alberto Corona"]);
    } else {
        mk_dir(matches.free, verb);
    }
}
